import { MaterialIcons } from 'taro-icons';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useEffect, useRef, useState } from 'react';
import { View, Text, Image, ScrollView} from '@tarojs/components';

import { IMAGE_BASE_URL } from '../../utils/common';
import PageHeader from '../../components/pageHeader';
import { DriverHospitalItem } from '../../types/myself';
import { useAppContext } from '../../contexts/AppContext';
import ProcessStatus from '../../components/processStep/processStatus';
import { NextButton } from '../../components/processStep/processButton';
import ProvinceCitySelector from '../../components/ProvinceCitySelector';

import { getUserLocationApi } from '../../api/user';
import { getChinaCityListApi, ChinaCityTree } from '../../api/cityApi';
import { 
  getProcessStepImageApi, getDriverHospitalApi, 
  getUserProgressStepApi, getUserApplyCityApi, 
  setProcessChildrenStatusApi } from '../../api/myself';

import './index.scss';


const UserDriveHospital: React.FC = () => {
  const router = useRouter();
  const firstLoadRef = useRef<boolean>(false);
  const stepId = router.params.stepId as string;
  const [userStep, setUserStep] = useState<any>({
    id: 0, name: "", children: [], completed_time: ""
  });
  const { setCarSubjectStepProcessStatus } = useAppContext();
  const [currentCity, setCurrentCity] = useState<string>("");
  const [chinaCity, setChinaCity] = useState<ChinaCityTree[]>([]);
  const [stepChild1, setStepChild1] = useState<string>("完成该步骤");
  const [stepChild2, setStepChild2] = useState<string>("完成该步骤");
  const [stepChild3, setStepChild3] = useState<string>("完成该步骤");
  const [currentCityCode, setCurrentCityCode] = useState<number[]>([]);
  const [showTextContent, setShowTextContent] = useState<string>('image');
  const [showToggleButton, setShowToggleButton] = useState<boolean>(true);
  const [stepImage, setStepImage] = useState<Map<string, string>>(new Map());
  const [hospitalData, setHospitalData] = useState<DriverHospitalItem[]>([]);
  const [selectedRegionPath, setSelectedRegionPath] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(Number(stepId));
      if (res.code === 200 && res.data && res.data.length === 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          children: result.children?.split(',') || [],
          completed_time: result.created_at
        });
        setStepChild1(result.children && result.children.includes("1") ? "已完成" : "完成该步骤");
        setStepChild2(result.children && result.children.includes("2") ? "已完成" : "完成该步骤");
        setStepChild3(result.children && result.children.includes("3") ? "已完成" : "完成该步骤");
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  }

  // 切换文字版和图片版
  const toggleTextContentShow = (type: string) => {
    setShowTextContent(type);
  };

  // 获取流程步骤图片
  const getProcessStepImage = async () => {
    try {
      const res = await getProcessStepImageApi(Number(stepId));
      if (res.code === 200 && res.data) {
        const images = new Map();
        for (const item of res.data) {
          // 小程序端图片路径调整
          const imageUrl = item.image.startsWith('http') ? item.image : `${IMAGE_BASE_URL}${item.image.startsWith('/') ? item.image : `/${item.image}`}`;
          images.set(item.name, imageUrl);
        }
        setStepImage(images);
        if (!images.get('医院讲解')) {
          setShowTextContent('text');
          setShowToggleButton(false);
        }
      }
    } catch (error) {
      console.error('获取流程步骤图片失败:', error);
    }
  }

  // 获取驾驶员医院
  const getDriverHospital = async (city_id: number = 0) => {
    try {
      setIsLoading(true);
      const res = await getDriverHospitalApi(city_id);
      if (res.code === 200 && res.data) {
        setHospitalData(res.data);
      }
    } catch (error) {
      console.error('获取医院列表失败:', error);
      Taro.showToast({ title: '获取医院列表失败', icon: 'none' });
    } finally {
      setIsLoading(false);
    }
  }

  // 从用户位置获取城市信息
  const getUserCityFromLocation = async () => {
    try {
        await getUserLocationApi().then(res=> {
          if (res.code === 200) {
            console.log('从用户位置获取城市信息成功:', res.data);
            setCurrentCity(res.data.city);
            setCurrentCityCode([res.data.cityCode]);
            getDriverHospital(res.data.cityCode);
            console.log('从用户位置获取城市信息成功:', res.data.city);
          }
        })
    } catch (error) {
      console.error('从用户位置获取城市信息失败:', error);
    }
  }

  // 获取用户申请城市
  const getUserApplyCity = async () => {
    try {
      const res = await getUserApplyCityApi();
      console.log('获取用户申请城市:', res);
      if (res.code === 200 && res.data && res.data.city_code) {
        setCurrentCityCode(res.data.city_code);
        setCurrentCity(res.data.city_name);
        // 使用城市编码的最后一级（市级别）来获取医院
        if (res.data.city_code && res.data.city_code.length > 0) {
          getDriverHospital(res.data.city_code[res.data.city_code.length - 1]);
        }
      }else{
        getUserCityFromLocation();
      }
    } catch (error) {
      console.error('获取用户申请城市失败:', error);
      getUserCityFromLocation();
    }
  }

  // 获取中国城市树
  const getChinaCityTree = async () => {
    try {
      const res = await getChinaCityListApi();
      if (res.code === 200 && res.data) {
        const twoLevelData = res.data.map(province => {
          return {
            ...province,
            children: province.children ? province.children.map(city => {
              return {
                ...city,
                children: []
              };
            }) : []
          };
        });
        setChinaCity(twoLevelData);
      }
    } catch (error) {
      console.error('获取城市信息:', error);
    }
  };

  // 城市选择改变
  const onCityChange = (values: string[]) => {
    if (values.length === 0) {
      return;
    }
    else if (values.length === 1) {
      const province = chinaCity.find(p => p.id === Number(values[0]));
      const city = province?.children?.[0]
      setSelectedRegionPath([province?.id?.toString() || '', city?.id.toString() || '']);
      getDriverHospital(Number(city?.id));
      setCurrentCity(`${city?.name}`);
    }
    else {
      const cityCode = values[values.length - 1];
      getDriverHospital(Number(cityCode));
      
      // 更新当前城市名称
      const province = chinaCity.find(p => p.id.toString() === values[0]);
      if (province && province.children) {
        const city = province.children.find(c => c.id.toString() === values[1]);
        if (city) {
          setCurrentCity(`${city?.name}`);
        }
      }
    }
  }

  // 医院提示信息
  const hospitalTipInfo = () => {
    return (
      <View className='user-drive-hospital-tip text-base'>
        <Text className='user-drive-hospital-tip-icon'>
          <MaterialIcons name="warning" size={24} color='#ffc107'/>
        </Text>
        <Text>部分医院仅供参考,请根据实际情况选择</Text>
      </View>
    );
  };

  // 设置流程步骤子状态
  const setStepChildrenStatus = async (children: string, status: string) => {
    if (status == '已完成') return;
    try {
      const res = await setProcessChildrenStatusApi(Number(stepId), children, 3);
      if (res.code === 200 && res.data) {
        const msg = res.data.status === 1 ? "当前步骤已全部完成~" : '设置成功';
        Taro.showToast({ title: msg, icon: 'success' });
        setUserStep({
          ...userStep,
          status: res.data.status,
          completed_time: res.data.created_at,
          children: [...userStep.children, children]
        });
        if (children === "3") setStepChild3("已完成");
        else if (children === "2") setStepChild2("已完成");
        else if (children === "1") setStepChild1("已完成");
        setCarSubjectStepProcessStatus(Number(stepId), res.data.status);
      }
    } catch (err) {
      Taro.showToast({ title: '设置失败', icon: 'none' });
    }
  };

  // 继续完成下一个步骤
  const handleContinueNextStep = () => {
    Taro.navigateTo({
      url: '/pages/user-course/index'
    });
  };

  useEffect(() => {
    if (!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
      getChinaCityTree();
      getUserApplyCity();
      getProcessStepImage();
      
    }
  }, []);

  return (
    <View className="user-drive-hospital-page-container">
      <PageHeader title="驾驶员体检" />
      {userStep.completed_time && (
        <ProcessStatus title="驾驶员体检" createTime={userStep.completed_time} />
      )}

      {/* 主内容区 */}
      <ScrollView className="user-drive-hospital-content-wrapper" scrollY>
        {/* 医院讲解部分 */}
        <View className={`user-drive-hospital-flip-card ${showTextContent ? 'user-drive-hospital-flipped' : ''}`}>
          <View className="user-drive-hospital-card-title-container">
            <Text className="user-drive-hospital-card-title">医院讲解</Text>
            {showToggleButton && (
              <View className='toggle-button-group'>
                <View className={`card-toggle-button ${showTextContent === 'image' ? 'toggle-button-active' : ''}`} onClick={() => toggleTextContentShow('image')}>
                  图片版
                </View>
                <View className={`card-toggle-button ${showTextContent === 'text' ? 'toggle-button-active' : ''}`} onClick={() => toggleTextContentShow('text')}>
                  文字版
                </View>
            </View>
            )}
          </View>
          
          <View className={`user-drive-hospital-flip-card-content ${showTextContent === 'text' ? 'user-drive-hospital-hidden' : ''}`}>
            {stepImage.get('医院讲解') && (
              <View className="user-drive-hospital-card-image">
                <Image 
                  src={stepImage.get('医院讲解') || ''}
                  mode='aspectFit'
                  onClick={() => Taro.previewImage({
                    current: stepImage.get('医院讲解') || '',
                    urls: [stepImage.get('医院讲解') || '']
                  })}
                />
              </View>
            )}
          </View>
          
          <View className={`user-drive-hospital-flip-card-content ${showTextContent === 'text' ? '' : 'user-drive-hospital-hidden'}`}>
            <View className="user-drive-hospital-requirements-list">
              <Text className='user-drive-hospital-requirements-title text-md'>驾驶员体检(初领)：</Text>
              <View className="user-drive-hospital-requirements-items">
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">1. </Text>
                  <Text className='text-base'>各位学员早上早点去排队，带好有效身份证。</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">2. </Text>
                  <Text className='text-base'>不抽血、不化验，不需要空腹。</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">3. </Text>
                  <Text className='text-base'>穿深色上衣，可化淡妆，需要拍照，近视带好眼镜。</Text>
                </View>
              </View>
            </View>

            <View className="user-drive-hospital-requirements-list">
              <Text className='user-drive-hospital-requirements-title text-md'>体检要求：</Text>
              <View className="user-drive-hospital-requirements-items">
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">1. 身高：</Text>
                  <Text className='text-base'>申请中型车辆身高要求150以上，小型汽车驾驶证没这个要求，一半去体检这项都能合格</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">2. 视力：</Text>
                  <Text className='text-base'>两眼裸视力或者矫正视力达到对数视力表4.9以上</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">3. 辨色力：</Text>
                  <Text className='text-base'>无红绿色盲</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">4. 听力：</Text>
                  <Text className='text-base'>两耳分别距音叉50厘米能辨别声源方向，有听力障碍带助听器设备能够达到以上条件的</Text>
                </View>
                <View className="user-drive-hospital-requirement-item">
                  <Text className="user-drive-hospital-requirement-number text-base">5. 上肢：</Text>
                  <Text className='text-base'>双手拇指健全，每只手其他手指必须要三指健全，肢体和手指运动功能正常</Text>
                </View>
                <View className="user-drive-hospital-requirement-item text-base">
                  <Text className="user-drive-hospital-requirement-number text-base">6. 下肢：</Text>
                  <Text className='user-drive-hospital-text text-base'>
                    双下肢健全且运动功能正常，申请驾驶手动挡汽车，下肢不等长度不得大于5厘米，
                    右下肢健全但左下肢缺失或者丧失运动功能的，可以申请小型自动挡汽车的机动车驾驶证
                  </Text>
                </View>
                <View className="user-drive-hospital-requirement-item text-base">
                  <Text className="user-drive-hospital-requirement-number text-base">7. 躯干、颈部：</Text>
                  <Text className='text-base'>无运动功能障碍</Text>
                </View>
              </View>
            </View>

            {/* 特别提醒 */}
            <View className="user-drive-hospital-reminder-card">
              <Text className="user-drive-hospital-reminder-title text-md">特别提醒</Text>
              <Text className="user-drive-hospital-reminder-content text-base">
                有些医院只做换证体检，没有拍照，各位学车人员要问清楚，不要耽误时间，初拿驾驶人体检是需要拍照的。
              </Text>
            </View>
          </View>
        </View>

        {/* 流程步骤 */}
        <View className="user-drive-hospital-process-card">
          <Text className="user-drive-hospital-card-title text-lg">体检流程</Text>
          <View className="user-drive-hospital-process-steps text-md">
            <View className={stepChild1 === "已完成" ? "user-drive-hospital-process-step user-hospital-step-active" : "user-drive-hospital-process-step"}>
              <View className="user-drive-hospital-step-number text-md">1</View>
              <View className="user-drive-hospital-step-content">
                <Text className="text-md">找到可以体检和拍照的医院</Text>
                <View 
                  onClick={() => setStepChildrenStatus("1", stepChild1)}
                  className={stepChild1 === "已完成" ? "user-drive-hospital-step-content-btn user-hospital-btn-active" : "user-drive-hospital-step-content-btn"}
                >
                  {stepChild1}
                </View>
              </View>
            </View>
            
            <View className={stepChild2 === "已完成" ? "user-drive-hospital-process-step user-hospital-step-active" : "user-drive-hospital-process-step"}>
              <View className="user-drive-hospital-step-number text-md">2</View>
              <View className="user-drive-hospital-step-content text-md">
                <Text className="text-md">完成体检</Text>
                <View 
                  onClick={() => setStepChildrenStatus("2", stepChild2)}
                  className={stepChild2 === "已完成" ? "user-drive-hospital-step-content-btn user-hospital-btn-active" : "user-drive-hospital-step-content-btn"}
                >
                  {stepChild2}
                </View>
              </View>
            </View>
            
            <View className={stepChild3 === "已完成" ? "user-drive-hospital-process-step user-hospital-step-active" : "user-drive-hospital-process-step"}>
              <View className="user-drive-hospital-step-number text-md">3</View>
              <View className="user-drive-hospital-step-content text-md">
                <Text className="text-md">完成拍照</Text>
                <View 
                  onClick={() => setStepChildrenStatus("3", stepChild3)}
                  className={stepChild3 === "已完成" ? "user-drive-hospital-step-content-btn user-hospital-btn-active" : "user-drive-hospital-step-content-btn"}
                >
                  {stepChild3}
                </View>
              </View>
            </View>
          </View>
          
          {/* 完成按钮 */}
          {userStep.status === 1 && (
            <View className="user-drive-hospital-completion-section">
              <NextButton onClick={handleContinueNextStep}/>
            </View>
          )}
        </View>

        {/* 城市选择和医院列表 */}
        <View className="user-drive-hospital-card">
          <View className="user-drive-hospital-card-title-container">
            <ProvinceCitySelector 
              level="city"
              chinaRegions={chinaCity}
              onSelect={onCityChange}
              selectedRegionPath={selectedRegionPath}
            >
              <View className="user-drive-hospital-city text-base">
                当前城市: {currentCity}
              </View>
            </ProvinceCitySelector>
            {hospitalTipInfo()}
          </View>


          {/* 医院列表 */}
          <View className="user-drive-hospital-list">
            {isLoading ? (
              <View className="user-drive-hospital-loading-container">
                <Text className="user-drive-hospital-loading-text text-base">加载中...</Text>
              </View>
            ) : hospitalData.length > 0 ? (
              hospitalData.map(hospital => (
                <View key={hospital.id} className="user-drive-hospital-item">
                  <Text className="user-drive-hospital-name text-base">{hospital.name}</Text>
                  <Text className="user-drive-hospital-address text-base">{hospital.address}</Text>
                  <View className="user-drive-hospital-worktime-section">
                    <Text className="user-drive-hospital-section-title text-base">工作时间：</Text>
                    <Text className="user-drive-hospital-worktime-weekdays text-base">{hospital.worktime}</Text>
                  </View>
                  <View className="user-drive-hospital-phone-section">
                    <Text className="user-drive-hospital-section-title text-base">电话：</Text>
                    <Text className="user-drive-hospital-phone-number text-base">{hospital.phone}</Text>
                  </View>
                </View>
              ))
            ) : (
              <View className="user-drive-hospital-empty-container">
                <Text className="user-drive-hospital-empty-text text-base">暂无医院信息</Text>
              </View>
            )}
          </View>
          
          {/* 底部提示 */}
          <View className="user-drive-hospital-bottom-tips">
            <View className="user-drive-hospital-bottom-tip">
              <MaterialIcons name="warning" size={24} color="#ffc107" className='user-drive-hospital-tip-icon'/>
              <Text className="text-base">部分医院需提前预约，数据仅供参考</Text>
            </View>
            <Text className="user-drive-hospital-bottom-tip2 text-base">数据来源网友,请拨打相关电话咨询后选择,平台不负任何责任</Text>
          </View>
        </View>

      </ScrollView>
    </View>
  );
};

export default UserDriveHospital;